package cn.jsp.dao;

import cn.jsp.domain.Stu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class StuDao {
  @Autowired DataSource dataSource;
  //显示stu表里所有数据
  public List<Stu> query(){
    List<Stu> res=new ArrayList<>();
    try (
      Connection connection = dataSource.getConnection();
      PreparedStatement preparedStatement = connection.prepareStatement("select * from stu");
      ResultSet rs = preparedStatement.executeQuery();){
      while (rs.next()){
        //把一行ResultSet转为一个Stu，ResultSet->Stu
        Stu stu=new Stu();
        stu.setAge(rs.getInt("age"));
        stu.setName(rs.getString("name"));
        res.add(stu);
      }
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
    return res;
  }
}
